package vip.hello520.service;

import com.alicp.jetcache.anno.Cached;
import org.springframework.beans.factory.annotation.Autowired;
import vip.hello520.mapper.BiYingImgNamePoMapper;
import vip.hello520.mapper.LinkPoMapperCustom;
import vip.hello520.model.BiYingImgNamePo;
import vip.hello520.model.LinkPo;
import vip.hello520.model.ResultBean;
import vip.hello520.model.ResultEnum;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * @author Hello
 * 如果加了@Service注解,就可以不用在dubbo配置文件里配置bean了,默认是类名首字母小写
 */
public class LinkServiceImpl implements LinkService {
    @Autowired
    private LinkPoMapperCustom linkPoMapperCustom;
    @Autowired
    private BiYingImgNamePoMapper biYingImgNamePoMapper;

    @Override
    //@CacheUpdate和@CacheInvalidate的name和area属性必须和@Cached相同，name属性还会用做cache的key前缀
    @Cached(name = "getLinkPoList-", expire = 60 * 60 * 24)
    public List<LinkPo> getLinkPoList() throws Exception {
        return linkPoMapperCustom.getLinksList();
    }

    @Override
    public ResultBean saveBiYingImgToRemote(String fileUrl, String savePath, String fileName) throws Exception {
        ResultBean resultBean = new ResultBean();
        File dir = new File(savePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdir();
        }
        URL urlAddress = new URL(fileUrl);
        //打开链接
        HttpURLConnection con = (HttpURLConnection) urlAddress.openConnection();
        //创建输入流
        try (BufferedInputStream inputStream = new BufferedInputStream(con.getInputStream());
             //创建输出流
             BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(dir, fileName)))) {
            //缓存数组
            byte[] by = new byte[1024];
            //input读取的字节数
            int len;
            while ((len = inputStream.read(by)) != -1) {
                outputStream.write(by, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultBean.setMessage(e.getMessage());
            resultBean.setState(ResultEnum.FAILURE.getStateInt());
            return resultBean;
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        BiYingImgNamePo po = new BiYingImgNamePo();
        po.setName(fileName);
        po.setDate(new Date());
        //保存图片名称到数据库BiYingImaName表
        biYingImgNamePoMapper.insert(po);
        resultBean.setMessage(ResultEnum.SUCCESS.getStateStr());
        resultBean.setState(ResultEnum.SUCCESS.getStateInt());
        return resultBean;
    }
}
